package com.feiyu.gateway.filter;

import com.feiyu.gateway.entity.accountInfoEntity;
import com.feiyu.gateway.feign.AccountFeign;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @Author: Doate
 * @Date: Created in 2021/4/12 19:10
 * @Description:
 */

@Component
public class FeiyuGateWayFilter implements GlobalFilter, Ordered {

    @Resource
    AccountFeign accountFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        exchange.getResponse().getHeaders().set("Access-Control-Expose-Headers", "token,isOk");

        exchange.getResponse().getHeaders().add("isOk", "true");
        if (request.getURI().toString().contains("openFeiyu")) {
            return chain.filter(exchange);
        }
        accountInfoEntity info = new accountInfoEntity();
        info.setIsTrue(false);
        String token = "";
        if (request.getHeaders().getFirst("token") != null) {
            token = request.getHeaders().get("token").get(0);
            info = accountFeign.loginCheck(token);
        }


        if (!info.getIsTrue()) {
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            exchange.getResponse().getHeaders().set("isOk", "false");

            return exchange.getResponse().setComplete();
        } else {
            request.mutate().header("userId",info.getUserId().toString())
                    .header("userName",info.getUserName())
                    .header("userPower", info.getUserPower().toString()).build();
//            request.getHeaders().set("userId", info.getUserId().toString());
//            request.getHeaders().set("userName", info.getUserName());
//            request.getHeaders().set("userPower", info.getUserPower().toString());

            return chain.filter(exchange.mutate().request(request).build());
        }


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
